package com.tsinghuabigdata.edu.ddmath.module.ddwork;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.tsinghuabigdata.edu.ddmath.MVPModel.MyStudyModel;
import com.tsinghuabigdata.edu.ddmath.MVPModel.RequestListener;
import com.tsinghuabigdata.edu.ddmath.R;
import com.tsinghuabigdata.edu.ddmath.ZxApplication;
import com.tsinghuabigdata.edu.ddmath.activity.RoboForToolBarActivity;
import com.tsinghuabigdata.edu.ddmath.bean.LoginInfo;
import com.tsinghuabigdata.edu.ddmath.bean.UserDetailinfo;
import com.tsinghuabigdata.edu.ddmath.commons.http.HttpResponse;
import com.tsinghuabigdata.edu.ddmath.module.ddwork.adapter.DDWorkPageAdapter;
import com.tsinghuabigdata.edu.ddmath.module.ddwork.adapter.DDWorkQuestionAdapter;
import com.tsinghuabigdata.edu.ddmath.module.ddwork.bean.DDWorkDetail;
import com.tsinghuabigdata.edu.ddmath.module.ddwork.bean.LocalPageInfo;
import com.tsinghuabigdata.edu.ddmath.module.ddwork.bean.LocalWorkInfo;
import com.tsinghuabigdata.edu.ddmath.module.ddwork.bean.QuestionInfo;
import com.tsinghuabigdata.edu.ddmath.module.ddwork.bean.WorkPageInfo;
import com.tsinghuabigdata.edu.ddmath.module.neteaseim.base.util.NetworkUtil;
import com.tsinghuabigdata.edu.ddmath.util.AccountUtils;
import com.tsinghuabigdata.edu.ddmath.util.AlertManager;
import com.tsinghuabigdata.edu.ddmath.util.AppLog;
import com.tsinghuabigdata.edu.ddmath.util.ToastUtils;
import com.tsinghuabigdata.edu.ddmath.view.LoadingView;

import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;

/**
 * 豆豆作业上传界面
 */
public class DDUploadActivity extends RoboForToolBarActivity implements WorkCommitListener, View.OnClickListener, AdapterView.OnItemClickListener{

    public static final String PARAM_DDWORKID = "ddworkid";
    public static final String PARAM_TITLE    = "title";

    @ViewInject(R.id.loadingView)
    private LoadingView mLoadingView;

    //页List
    @ViewInject(R.id.ddwork_list_worklist)
    private ListView pageListView;

    @ViewInject(R.id.ddwork_list_cameralayout)
    private RelativeLayout mCameraLayout;
    @ViewInject( R.id.ddwork_list_camerabtn )
    RelativeLayout mCameraBtn;
    @ViewInject( R.id.ddwork_list_cameratext )
    private TextView cameraTextView;

    //作业状态
    @ViewInject( R.id.ddwork_list_workstatuslayout )
    private RelativeLayout workStatusLayout;
    @ViewInject(R.id.ddwork_list_workstatus)
    private TextView workStatusView;

    //已批阅
    //@ViewInject(R.id.)
    //private RelativeLayout correctedLayout;

    @ViewInject( R.id.ddwork_list_qustionlist )
    private ListView questionListView;

    private Context mContext;
    //
    private DDWorkPageAdapter mPageAdapter;
    private DDWorkQuestionAdapter mQuestionAdapter;

    private MyStudyModel myStudyModel;
    private LocalWorkInfo localWorkInfo;

    //
    private String ddworkId;
    private String title;

    private Activity mActivity;
    @Override
    protected int getContentViewId() {
        return R.layout.activity_ddwork_list;
    }

    @Override
    protected void onCreate( Bundle savedInstanceState){
        super.onCreate(savedInstanceState);

        //setTitle("待上传图册");
        setLeftTitle( "返回", R.color.white );
        setBarTextcolor(R.color.white);
        setUserBarBackgroud(true);

        x.view().inject(this);

        mContext = this;
        mActivity = this;

        if( !parseIntent() ){
            ToastUtils.show( mContext, "参数错误", Toast.LENGTH_SHORT );
            finish();
            return;
        }

        initView();
        loadData();
    }

    @Override
    public void onResume(){
        super.onResume();

        //触发刷新
        mQuestionAdapter.notifyDataSetChanged();
        mPageAdapter.notifyDataSetChanged();

        //更新作业状态
        setWorkStatus( localWorkInfo.getWorkStatus() );

    }
    @Override
    public void onLeftClick(){
        finish();
    }

    @Override
    public void onBackPressed(){
        finish();
    }

    @Override
    public void onDestroy(){
        super.onDestroy();

        //停止上传监听
        DDWorkManager manager = DDWorkManager.getDDWorkManager();
        if( manager!=null ){
            manager.removeCommitListener( this );
        }

    }

    @Override
    public void onClick(View v) {
        if( R.id.ddwork_list_camerabtn == v.getId() ){
            int index = mPageAdapter.getSelectIndex();
            if( index < 0 ){
                ToastUtils.show( mContext, "请先选择作业页面", Toast.LENGTH_SHORT );
                return;
            }

            Intent intent = new Intent( mContext, DDCameraActivity.class );
            intent.putExtra( DDWorkUtil.WORK_ID, ddworkId );
            intent.putExtra( DDWorkUtil.PAGEINDEX, index );
            startActivity( intent );

        }else if( R.id.ddwork_list_workstatuslayout == v.getId()  ){

            //网络检测
            if( !NetworkUtil.isNetAvailable( ZxApplication.getApplication() ) ){
                ToastUtils.showToastCenter( mContext, getResources().getString( R.string.ddwork_commitfail_tips) );
                return;
            }

            if( localWorkInfo == null ){
                ToastUtils.showShort( mContext, "作业信息错误!" );
                finish();
                return;
            }
            //先检查
            String msg = checkUnCameraPage();
            if( TextUtils.isEmpty(msg) ){   //全部已拍摄
                //开始上传
                startCommitData();
            }else{      //有页面没有拍摄
                AlertManager.showCustomDialog1( mContext, msg, "确定", "取消", new DialogInterface.OnClickListener(){
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        startCommitData();
                    }
                },null );
            }
        }
    }

    @Override
    public void workStatus(final String examId, final int status) {
        AppLog.i("dfdfdsfds  workStatus examId = " + examId + ",,, status = " + status );
        if( localWorkInfo == null ) return;

        mActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if( examId.equals( localWorkInfo.getWorkId() ) ){
                    setWorkStatus( status );
                }
            }
        });
    }

    //每一页的状态
    @Override
    public void pageStatus( final String examId, final int status) {
        AppLog.i("dfdfdsfds  pageStatus examId = " + examId + ",,, status = " + status );

        if( localWorkInfo == null ) return;

        mActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if( examId.equals( localWorkInfo.getWorkId() ) ){
                    mPageAdapter.notifyDataSetChanged();
                }
            }
        });

    }

    //整个作业的状态
    @Override
    public void onSuccess( final String examId, Boolean status) {
        if( !examId.equals( localWorkInfo.getWorkId() ) ) return;

        AppLog.i("dfdfdsfds  onSuccess status = " +  status );
        setWorkStatus( status?LocalWorkInfo.WORK_COMMITED:LocalWorkInfo.WORK_COMMITFAIL );
        if( status ){
            mActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ToastUtils.showToastCenter( mContext, "提交成功" );
                    //隐藏拍照层
                    mCameraLayout.setVisibility( View.GONE );
                }
            });
        }else{
            ToastUtils.showToastCenter( mContext, getResources().getString( R.string.ddwork_commitfail_tips2) );
        }
    }

    @Override
    public void onFail( final String examId, Exception ex ) {
        if( !examId.equals( localWorkInfo.getWorkId() ) ) return;

        AppLog.i("dfdfdsfds  onFail ex = " +  ex.toString() );
        setWorkStatus( LocalWorkInfo.WORK_COMMITFAIL );

        if( ex.getMessage()!=null && ex.getMessage().contains("网络") ){
            ToastUtils.showToastCenter( mContext, getResources().getString( R.string.ddwork_commitfail_tips) );
        }else{
            ToastUtils.showToastCenter( mContext, getResources().getString( R.string.ddwork_commitfail_tips2) );
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //选中状态改变
        LocalPageInfo pageInfo = mPageAdapter.getItem( position );
        mPageAdapter.selectItem( position );
        setCameraText( pageInfo );

        //题目内容改变
        mQuestionAdapter.clear();
        mQuestionAdapter.addQuestionList( pageInfo.getQuestions(), position+1 );
        mQuestionAdapter.notifyDataSetChanged();
    }


    //----------------------------------------------------------------------
    private boolean parseIntent(){
        Intent intent = getIntent();
        ddworkId = intent.getStringExtra( PARAM_DDWORKID );
        title    = intent.getStringExtra( PARAM_TITLE );

        return !( TextUtils.isEmpty( ddworkId ) || TextUtils.isEmpty(title) );
    }

    //
    private void startCommitData(){

        AlertManager.showCustomDialog1( mContext, getResources().getString(R.string.ddwork_commit_tips), "确定并提交", "取消", new DialogInterface.OnClickListener(){
            @Override
            public void onClick(DialogInterface dialog, int which) {
                localWorkInfo.startUploadData();
            }
        },null );
    }

    //检查是否有页面没有拍照，返回相关信息
    private String checkUnCameraPage(){
        String data = "";

        int count = mPageAdapter.getCount();
        for( int i=0; i<count; i++ ){
            LocalPageInfo pageInfo = mPageAdapter.getItem(i);
            if( TextUtils.isEmpty(pageInfo.getLocalpath()) ){
                if( TextUtils.isEmpty(data) ){
                    data = "第"+String.valueOf(i+1);
                }else{
                    data += ",";
                    data += String.valueOf(i+1);
                }
            }
        }
        if( !TextUtils.isEmpty(data) ){
            data += "页作业未拍摄，你确定要上传吗?";
        }
        return data;
    }

    //检查作业是否已拍照
    private boolean hasLocalImage(){
        int count = mPageAdapter.getCount();
        for( int i=0; i<count; i++ ){
            LocalPageInfo pageInfo = mPageAdapter.getItem(i);
            if( !TextUtils.isEmpty(pageInfo.getLocalpath()) ){
                return true;
            }
        }
        return false;
    }

    private void setWorkStatus( int status ){
        if( LocalWorkInfo.WORK_NONE == status ){
            workStatusView.setText("提交作业");
            if( hasLocalImage() ){
                workStatusLayout.setEnabled( true );
                workStatusLayout.setBackgroundColor( getResources().getColor( R.color.color_48B8FF ) );
            }else{
                workStatusLayout.setEnabled( false );
                workStatusLayout.setBackgroundColor( getResources().getColor( R.color.color_D4EEFF ) );
            }
        }else if( LocalWorkInfo.WORK_COMMITING == status ){
            workStatusView.setText("正在提交");
            workStatusLayout.setBackgroundColor( getResources().getColor( R.color.color_59CDBE ) );

            Drawable drawable = getResources().getDrawable(R.drawable.ic_refresh);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            workStatusView.setCompoundDrawables( null, null, drawable, null );

        }else if( LocalWorkInfo.WORK_COMMITED == status ){
            workStatusView.setText("待批阅");
            workStatusView.setCompoundDrawables( null, null, null, null );
            workStatusLayout.setBackgroundColor( getResources().getColor( R.color.color_FFB555 ) );
        }else if( LocalWorkInfo.WORK_COMMITFAIL == status ){
            workStatusView.setText("重新提交");
            workStatusView.setCompoundDrawables( null, null, null, null );
            workStatusLayout.setBackgroundColor( getResources().getColor( R.color.color_FF7555 ) );
        }
    }

    private void initView(){

        //标题
        setTitle( title, R.color.white );

        mCameraBtn.setOnClickListener( this );

        mPageAdapter = new DDWorkPageAdapter( mContext, DDWorkDetail.WORK_UNSUBMIT );
        pageListView.setAdapter( mPageAdapter );
        pageListView.setOnItemClickListener( this );

        mQuestionAdapter = new DDWorkQuestionAdapter( mContext );
        questionListView.setAdapter( mQuestionAdapter );

        workStatusLayout.setOnClickListener( this );

        mLoadingView.setListener(new View.OnClickListener() {           //失败点击重新加载
            @Override
            public void onClick(View v) {
                loadData();
            }
        });

        myStudyModel = new MyStudyModel();

        DDWorkManager manager = DDWorkManager.getDDWorkManager();
        if( manager!=null ){
            manager.addCommitListener( this );
        }
    }

    //加载的是本地保存的数据
    private void loadData(){

        LoginInfo loginInfo = AccountUtils.getLoginUser();
        UserDetailinfo detailinfo = AccountUtils.getUserdetailInfo();
        if( loginInfo == null || detailinfo == null /*|| detailinfo.getJoinedClassInfoList()==null || detailinfo.getJoinedClassInfoList().size()==0*/ ){
            ToastUtils.show( mContext, "请登录", Toast.LENGTH_SHORT );
            return;
        }

        String accessToken = loginInfo.getAccessToken();
        String studentId   = detailinfo.getStudentId();
        //String classId     = detailinfo.getJoinedClassInfoList().get(0).getClassId();

//        DDWorkDetail workDetail = new DDWorkDetail();
//        workDetail.setPageCount( 2 );
//
//        ArrayList<LocalPageInfo> pageList = new ArrayList<>();
//        workDetail.setPageInfo( pageList );
//
//        LocalPageInfo localPageInfo = new LocalPageInfo( ddworkId );
//        localPageInfo.setPageNum( 1 );
//
//
//        ArrayList<LocalQuestionInfo> questionInfos = new ArrayList<>();
//        localPageInfo.setQuestions( questionInfos );
//
//        LocalQuestionInfo questionInfo = new LocalQuestionInfo();
//        questionInfo.setQuestionId( "stdjkfdjjdsksdfjfkjdsf" );
//        questionInfo.setQuestionType( QuestionInfo.TYPE_CHOICE );
//        questionInfo.setIndexInPaper( 1 );
//        questionInfo.setStem( "1. 下列3条线段能构成三角形的是：" );
//        questionInfo.setSubStem( "     A.1,2,3\n    B.20,20,30\n    C.30,10,15\n    D.4,15,7" );
//        questionInfo.setQuestionArea("[{\"x\":0, \"y\":0.1, \"width\":1.0, \"height\":0.2}]");
//        questionInfos.add( questionInfo );
//
//        questionInfo = new LocalQuestionInfo();
//        questionInfo.setQuestionId( "wewewewexcfvdsgfdgfdgfgf" );
//        questionInfo.setQuestionType( QuestionInfo.TYPE_FILL_IN );
//        questionInfo.setIndexInPaper( 2 );
//        questionInfo.setStem( "1. 一列火车每小时行78.5千米，x小时行（            ）千米。" );
//        questionInfo.setQuestionArea("[{\"x\":0.5, \"y\":0.4, \"width\":0.8, \"height\":0.4}]");
//        questionInfos.add( questionInfo );
//
//        workDetail.getPageInfo().add( localPageInfo );
//
//        //-------------------------------------------
//        //第二页
//
//        localPageInfo = new LocalPageInfo( ddworkId );
//        localPageInfo.setPageNum( 2 );
//
//        questionInfos = new ArrayList<>();
//        localPageInfo.setQuestions( questionInfos );
//
//        questionInfo = new LocalQuestionInfo();
//        questionInfo.setQuestionId( "stdjkfdjjdsksdfjfkjdsf" );
//        questionInfo.setQuestionType( QuestionInfo.TYPE_FILL_IN );
//        questionInfo.setIndexInPaper( 1 );
//        questionInfo.setStem( "2. 22222 下列3条线段能构成三角形的是：" );
//        questionInfo.setSubStem( "     A.1,2,3\n    B.20,20,30\n    C.30,10,15\n    D.4,15,7" );
//        questionInfo.setQuestionArea("[{\"x\":0, \"y\":0.1, \"width\":1.0, \"height\":0.2}]");
//        questionInfos.add( questionInfo );
//
//        questionInfo = new LocalQuestionInfo();
//        questionInfo.setQuestionId( "wewewewexcfvdsgfdgfdgfgf" );
//        questionInfo.setQuestionType( QuestionInfo.TYPE_FILL_IN );
//        questionInfo.setIndexInPaper( 2 );
//        questionInfo.setStem( "3. 2222 一列火车每小时行78.5千米，x小时行（            ）千米。" );
//        questionInfo.setQuestionArea("[{\"x\":0.5, \"y\":0.4, \"width\":0.8, \"height\":0.3}]");
//        questionInfos.add( questionInfo );
//
//        questionInfo = new LocalQuestionInfo();
//        questionInfo.setQuestionId( "sssssdfgdbhghjjhjkj" );
//        questionInfo.setQuestionType( QuestionInfo.TYPE_SOLUTION );
//        questionInfo.setIndexInPaper( 3 );
//        questionInfo.setStem( "1. 某校进行野外军训，甲、乙两队同时从学校出发。两队白天的行走速度是不同的，甲队每个白天行20千米，乙队行15千米，夜里两队的行走速度是相同的，结果甲队恰好用5个昼夜达目" );
//        questionInfo.setQuestionArea("[{\"x\":0, \"y\":0.8, \"width\":0.95, \"height\":0.1}]");
//        questionInfos.add( questionInfo );
//
//        workDetail.getPageInfo().add( localPageInfo );


        mLoadingView.showLoading();
        myStudyModel.queryDDWorkDetail(accessToken, studentId, ddworkId, new RequestListener() {
            @Override
            public void onSuccess(Object res) {

                DDWorkDetail workDetail = (DDWorkDetail)res;

                ArrayList<LocalPageInfo> list = localWorkInfo.getPageList();
                //首页加载 错误 或者没有数据   显示无
                if( list == null || list.size() == 0 ){
                    mLoadingView.showFaultView( true );
                    return;
                }

                //显示拍照层
                mCameraLayout.setVisibility(View.VISIBLE);
                mLoadingView.hideall();

                //对题型进行分析，
                int index = 0;
                for(WorkPageInfo pageInfo : workDetail.getPageInfo() ){
                    index++;
                    for(QuestionInfo questionInfo1 : pageInfo.getQuestions() ){
                        mQuestionAdapter.addQuestionType( questionInfo1.getQuestionType(), index );
                    }
                }

                //作业信息与本地数据进行关联处理
                DDWorkManager ddWorkManager = DDWorkManager.getDDWorkManager();
                if( ddWorkManager == null ){
                    ToastUtils.show( mContext, "DDWorkManager 管理器没有初始化", Toast.LENGTH_SHORT );
                    return;
                }
                workDetail.setWorkId( ddworkId );
                localWorkInfo = ddWorkManager.relateLocalWorkInfo( workDetail );

                //更新作业状态
                setWorkStatus( localWorkInfo.getWorkStatus() );

                //默认第一页被选中
                LocalPageInfo localPageInfo1 = list.get( 0 );
                setCameraText( localPageInfo1 );

                mQuestionAdapter.clear();
                mQuestionAdapter.addQuestionList( localPageInfo1.getQuestions(), 1 );
                mQuestionAdapter.notifyDataSetChanged();

                //如果是下拉加载，清除原列表数据
                mPageAdapter.clear();
                mPageAdapter.addAll( list );
                mPageAdapter.notifyDataSetChanged();

            }

            @Override
            public void onFail(HttpResponse response, Exception ex) {
                mLoadingView.showFaultView( false );
            }
        });

    }

    private void setCameraText( LocalPageInfo localPageInfo ){
        localPageInfo.setSelected( true );
        if( TextUtils.isEmpty( localPageInfo.getLocalpath()) ){
            cameraTextView.setText("拍摄照片");
        }else{
            cameraTextView.setText("重新拍摄");
        }
    }

}

